package com.paic.mhis.hcpms.quota.exportword.jfreechart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberAxis3D;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.DialShape;
import org.jfree.chart.plot.MeterInterval;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.paic.mhis.core.exception.FwaBusinessException;
import com.paic.mhis.hcpms.quota.exportword.dto.BaseChartDTO;
import com.paic.mhis.hcpms.quota.exportword.dto.XYLineChartDataDTO;
import com.paic.mhis.hcpms.quota.exportword.itext.CreateRtfTableDataHelper;
import com.paic.mhis.hcpms.quota.exportword.utils.GeneralMethods;
import com.paic.mhis.hcpms.quota.settlement.common.KpiValueConst;

/**
 * jfreechart帮助类
 * 
 * @author: EX-XIONGFEI002
 * @version: 1.0
 */
@Component("jFreeChartHelper")
public class JFreeChartHelper {
	private static final Logger logger = Logger.getLogger(JFreeChartHelper.class);

	@Value("${rtfFileDownloadPath}")
	private String rtfReportDir;

	// 保留个位
	private static List<String> retainABitList = new ArrayList<String>();

	// 保留一位小数
	private static List<String> retainOneBitList = new ArrayList<String>();

	static {
		retainABitList.add("k0_2_3_2_cy_xyLine_img");
		retainABitList.add("k2_2_3_2_cy_xyLine_img");
		retainABitList.add("k0_3_3_2_cy_xyLine_img");
		retainABitList.add("k2_3_3_2_cy_xyLine_img");
		retainABitList.add("k0_3_4_2_zy_xyLine_img");
		retainABitList.add("k2_3_4_2_zy_xyLine_img");

		retainOneBitList.add("k0_2_4_2_zy_xyLine_img");
		retainOneBitList.add("k2_2_4_2_zy_xyLine_img");
	}

	private String getRate(Map<String, Object> paramMap) {
		// 同比、环比
		String yoy = null;
		if (paramMap.get("meter_rate_flag") instanceof BigDecimal) {
			yoy = (BigDecimal) paramMap.get("meter_rate_flag") == null ? "0" : String.valueOf(paramMap
					.get("meter_rate_flag"));
		} else {
			yoy = (String) paramMap.get("meter_rate_flag");
		}

		return yoy;
	}

	/**
	 * 转化同比环比值
	 * 
	 * @param rate
	 *            rate
	 * @param paramMap
	 *            paramMap
	 * @return 比值
	 */
	@SuppressWarnings("rawtypes")
	private double parseRate(String rate, Map paramMap) {
		double defaultValue = Double.parseDouble(rate);
		if ("降低".equals(paramMap.get("increaseFlag"))) {
			defaultValue = -defaultValue;
		}

		return defaultValue;
	}

	private JFreeChart createMeterChart(Map<String, Object> paramMap) {

		String yoyFlag = (String) paramMap.get("yoyFlag");

		String uperLimit = null;
		String lowerLimit = null;
		if ("0".equals(yoyFlag)) {
			uperLimit = (String) paramMap.get("meter_yoy_upper_limit");
			lowerLimit = (String) paramMap.get("meter_yoy_lower_limit");
		} else if ("1".equals(yoyFlag)) {
			uperLimit = (String) paramMap.get("meter_mom_upper_limit");
			lowerLimit = (String) paramMap.get("meter_mom_lower_limit");
		}

		if (uperLimit == null || lowerLimit == null || Double.parseDouble(uperLimit) <= Double.parseDouble(lowerLimit)) {
			return null;
		}

		String rate = getRate(paramMap);
		if (GeneralMethods.getInstance().isEmptyString(rate) || " ".equals(rate)) {
			return null;
		}

		double defaultValue = parseRate(rate, paramMap);

		// 正常范围内的最大最小值
		double maxNormal = Double.parseDouble(uperLimit);
		double minNormal = Double.parseDouble(lowerLimit);

		// 仪表盘的最大最小值
		double rangle = maxNormal - minNormal;
		double maxValue = Math.ceil(Double.parseDouble(uperLimit) + Math.abs(rangle) * 0.12);
		double minValue = Math.floor(Double.parseDouble(lowerLimit) - Math.abs(rangle) * 0.12);

		// 如果实际值超过仪表盘最大值，则充值仪表盘最大值
		if (defaultValue > Double.parseDouble(uperLimit)) {
			maxValue = Math.ceil(defaultValue);
		}
		if (defaultValue < Double.parseDouble(lowerLimit)) {
			minValue = Math.floor(defaultValue);
		}

		DefaultValueDataset data = new DefaultValueDataset(GeneralMethods.getInstance().parsePercentage(defaultValue));

		MeterPlot plot = new MeterPlot(data);
		plot.setBackgroundPaint(Color.WHITE);
		plot.setDialShape(DialShape.CHORD);
		plot.setDialBackgroundPaint(Color.WHITE);
		plot.setRange(new Range(GeneralMethods.getInstance().parsePercentage(minValue), GeneralMethods.getInstance()
				.parsePercentage(maxValue)));
		plot.setValueFont(new java.awt.Font("微软雅黑", com.lowagie.text.Font.NORMAL, 9));
		plot.setUnits(" ");
		// 刻度
		plot.setDialOutlinePaint(Color.GRAY);
		// 指针
		plot.setNeedlePaint(Color.GRAY);
		// 显示数据,保留两位小数
		NumberFormat percentInstance = NumberFormat.getPercentInstance();
		percentInstance.setMaximumFractionDigits(2);
		plot.setTickLabelFormat(percentInstance);

		plot.setTickLabelsVisible(true);
		plot.setTickLabelPaint(Color.BLACK);
		plot.setTickPaint(Color.GRAY);
		// 刻度大小，2%
		plot.setTickSize(GeneralMethods.getInstance().parsePercentage(2000));
		plot.setValuePaint(Color.BLACK);

		plot.addInterval(new MeterInterval("偏低", new Range(GeneralMethods.getInstance().parsePercentage(minValue),
				GeneralMethods.getInstance().parsePercentage(minNormal)), new Color(0, 176, 80), null, new Color(192,
				0, 0)));
		plot.addInterval(new MeterInterval("正常", new Range(GeneralMethods.getInstance().parsePercentage(minNormal),
				GeneralMethods.getInstance().parsePercentage(maxNormal)), new Color(0, 176, 80), null, new Color(0,
				176, 80)));

		plot.addInterval(new MeterInterval("偏高", new Range(GeneralMethods.getInstance().parsePercentage(maxNormal),
				GeneralMethods.getInstance().parsePercentage(maxValue)), new Color(0, 176, 80), null, new Color(192, 0,
				0)));

		createJfreeChartMetalTheme();

		// 创建chart，最后一个参数决定是否显示图例
		JFreeChart chart = new JFreeChart((String) paramMap.get("meter_title"), JFreeChart.DEFAULT_TITLE_FONT, plot,
				true);
		chart.setBackgroundPaint(Color.WHITE);

		return chart;
	}

	private void createJpegImg(String filePath, JFreeChart jfreechart, String bigPicFlag) {
		FileOutputStream file = null;
		try {
			file = new FileOutputStream(filePath);
			if (KpiValueConst.BIG_PIC.equals(bigPicFlag)) {
				// 510, 180
				ChartUtilities.writeChartAsJPEG(file, 1.0f, jfreechart, 510, 180, null);
			} else if (KpiValueConst.MEDIATE_PIC.equals(bigPicFlag)) {
				// 300, 300
				ChartUtilities.writeChartAsJPEG(file, 1.0f, jfreechart, 350, 350, null);
			} else if (KpiValueConst.BAR_PIC.equals(bigPicFlag)) {
				// 530, 260
				ChartUtilities.writeChartAsJPEG(file, 1.0f, jfreechart, 530, 260, null);
			} else {
				// 200, 200....
				ChartUtilities.writeChartAsJPEG(file, 1.0f, jfreechart, 200, 200, null);
			}
		} catch (FileNotFoundException e) {
			logger.error("--createJpegImg()---", e);
		} catch (IOException e) {
			logger.error("--createJpegImg()---", e);
		} finally {
			try {
				if (file != null) {
					file.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 创建同比、环比的仪表盘
	 * 
	 * @param resultMap
	 *            返回参数
	 * @param paramMap
	 *            入参
	 * @param imageName
	 *            要生成的图片名称
	 * @param dataKey
	 *            从接口取出来的同比、环比数据key
	 * @param rtfKey
	 *            存入resultMap的key
	 */
	public void createMeterChart(Map<String, Object> resultMap, Map<String, Object> paramMap, String rtfKey) {

		JFreeChart chart = createMeterChart(paramMap);

		try {

			String imageFilePath = CreateRtfTableDataHelper.getInstance().getImagesDir(paramMap, rtfReportDir) + rtfKey
					+ ".png";

			// 没有上下限或者没有同比环比,则不生成图片
			if (chart == null) {
				imageFilePath = "";
			} else {
				// 生成文档，然后保存到resultMap中，用例替换前端的占位符
				createJpegImg(imageFilePath, chart, KpiValueConst.SMALL_PIC);
			}

			resultMap.put(rtfKey, imageFilePath);

		} catch (FwaBusinessException e) {
			logger.error("--createMeterChart()---", e);
		}
	}

	/**
	 * 创建同比、环比的仪表盘
	 * 
	 * @param resultMap
	 *            返回参数
	 * @param paramMap
	 *            入参
	 * @param imageName
	 *            要生成的图片名称
	 * @param dataKey
	 *            从接口取出来的数据key
	 * @param rtfKey
	 *            存储图片路径的key
	 * @param isBigPic
	 *            是否生成大图
	 */
	@SuppressWarnings("unchecked")
	public void createXYLineChart(Map<String, Object> resultMap, Map<String, Object> paramMap, String rtfKey) {
		// 生成曲线图
		JFreeChart chart = createXYLineChart((BaseChartDTO) paramMap.get("xyLine_chartDTO"),
				(List<XYLineChartDataDTO>) paramMap.get("xyLine_chartDataDTO"));

		// 门诊人次、出院人次、门诊人数趋势图，保留到个位
		if (retainABitList.contains(rtfKey)) {
			XYPlot xyplot = chart.getXYPlot();
			NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
			rangeAxis.setNumberFormatOverride(new DecimalFormat("0"));
		} else if (retainOneBitList.contains(rtfKey)) {
			// 平均住院日：保留一位小数
			XYPlot xyplot = chart.getXYPlot();
			NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
			rangeAxis.setNumberFormatOverride(new DecimalFormat("0.0"));
		}

		try {
			String imageFilePath = CreateRtfTableDataHelper.getInstance().getImagesDir(paramMap, rtfReportDir) + rtfKey
					+ ".png";

			createJpegImg(imageFilePath, chart, KpiValueConst.BIG_PIC);

			resultMap.put(rtfKey, imageFilePath);

		} catch (FwaBusinessException e) {
			logger.error("--createXYLineChart ----", e);
		}

	}

	/**
	 * 生成混合图
	 * 
	 * @param resultMap
	 *            出参
	 * @param paramMap
	 *            入参
	 * @param imageName
	 *            图片名称
	 * @param rtfKey
	 *            map中保持的key
	 * @param bigPicFlag
	 *            是否大图标示
	 */
	@SuppressWarnings("unchecked")
	public void createCombinedChart(Map<String, Object> resultMap, Map<String, Object> paramMap, String rtfKey) {
		// 生成混合曲线图
		JFreeChart chart = createCombinedChart((BaseChartDTO) paramMap.get("xyLine_chartDTO"),
				(List<XYLineChartDataDTO>) paramMap.get("xyLine_chartDataDTO"));

		try {
			String imageFilePath = CreateRtfTableDataHelper.getInstance().getImagesDir(paramMap, rtfReportDir) + rtfKey
					+ ".png";

			createJpegImg(imageFilePath, chart, KpiValueConst.BIG_PIC);

			resultMap.put(rtfKey, imageFilePath);

		} catch (FwaBusinessException e) {
			logger.error("--createXYLineChart ----", e);
		}
	}

	/**
	 * 创建饼图图表 第一部分 4个 第三部分 6个
	 * 
	 * @param resultMap
	 *            返回参数
	 * @param paramMap
	 *            入参
	 * @param imageName
	 *            要生成的图片名称
	 * @param rtfKey
	 *            存储图片路径的key
	 * @param isBigPic
	 *            是否生成大图
	 */
	@SuppressWarnings("unchecked")
	public void createPieChartPic(Map<String, Object> resultMap, Map<String, Object> paramMap, String rtfKey,
			String bigPicFlag) {

		// 生成曲线图
		JFreeChart chart = createPieChart((BaseChartDTO) paramMap.get("xyLine_chartDTO"),
				(List<Object>) paramMap.get("xyLine_chartDataDTO"));

		try {
			String imageFilePath = CreateRtfTableDataHelper.getInstance().getImagesDir(paramMap, rtfReportDir) + rtfKey
					+ ".png";

			// 生成文档，然后保存到resultMap中，用来替换前端的占位符
			createJpegImg(imageFilePath, chart, bigPicFlag);

			resultMap.put(rtfKey, imageFilePath);

		} catch (FwaBusinessException e) {
			logger.error("--createPieChartPic ----", e);
		}
	}

	/**
	 * 创建饼图图表 第一部分 4个 第三部分 6个
	 * 
	 * @param resultMap
	 *            返回参数
	 * @param paramMap
	 *            入参
	 * @param imageName
	 *            要生成的图片名称
	 * @param rtfKey
	 *            存储图片路径的key
	 */
	public void createPieChartPic(Map<String, Object> resultMap, Map<String, Object> paramMap, String rtfKey) {
		createPieChartPic(resultMap, paramMap, rtfKey, KpiValueConst.MEDIATE_PIC);
	}

	/**
	 * 创建按时间为起点的折线图
	 * 
	 * @param baseChart
	 *            baseChartDTO
	 * @param xyDTO
	 *            xy data dto
	 * @return jfreechart
	 */
	private JFreeChart createXYLineChart(BaseChartDTO baseChart, List<XYLineChartDataDTO> xyDTOList) {

		IntervalXYDataset data1 = createXYLineDataset(xyDTOList, baseChart);

		createJfreeChartTheme();

		JFreeChart chart = ChartFactory.createTimeSeriesChart(baseChart.getChartName(), baseChart.getxName(),
				baseChart.getyName(), data1, true, true, false);

		XYPlot xyplot = chart.getXYPlot();
		// 设定显示的风格
		xyplot.setBackgroundPaint(Color.white);
		// 设置图形显示数据区域为灰白色
		xyplot.setDomainGridlinePaint(Color.white);
		// 设置图形显示区域的竖线为白色
		xyplot.setRangeGridlinePaint(Color.GRAY);
		xyplot.setRangeGridlineStroke(new BasicStroke(0.3f));

		// 设置曲线的颜色
		xyplot.setDrawingSupplier(getSupplier());
		// 显示曲线上的点
		XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
		xylineandshaperenderer.setBaseShapesVisible(true);

		// x轴格式
		DateAxis dateAxis = (DateAxis) xyplot.getDomainAxis();
		dateAxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM"));

		NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();

		// y轴格式 百分号
		if ("2".equals(baseChart.getyDataType())) {
			NumberFormat percentInstance = NumberFormat.getPercentInstance();
			percentInstance.setMaximumFractionDigits(1);
			rangeAxis.setNumberFormatOverride(percentInstance);
		} else {
			// NumberFormat numberInstance = NumberFormat.getNumberInstance();
			// numberInstance.setMaximumFractionDigits(1);
			// numberInstance.setMinimumFractionDigits(0);
			DecimalFormat df = new DecimalFormat("0.00");

			rangeAxis.setNumberFormatOverride(df);
		}

		return chart;

	}

	/**
	 * Creates an overlaid chart.
	 * 
	 * @param baseChart
	 *            baseChart
	 * @param xyDTOList
	 *            xyDTOList
	 * @return The chart.
	 */
	public JFreeChart createCombinedChart(BaseChartDTO baseChart, List<XYLineChartDataDTO> xyDTOList) {

		if (GeneralMethods.getInstance().isEmptyCollects(xyDTOList) || xyDTOList.size() < 2) {
			xyDTOList = new ArrayList<XYLineChartDataDTO>();
			xyDTOList.add(new XYLineChartDataDTO());
			xyDTOList.add(new XYLineChartDataDTO());
		}

		// create plot ...
		IntervalXYDataset data1 = createXYLineDataset(xyDTOList.subList(0, 1), baseChart);

		createJfreeChartTheme();

		// 其实这里应该是第一个y坐标,所以用的xname
		JFreeChart chart = ChartFactory.createXYLineChart(baseChart.getChartName(), "", baseChart.getxName(), data1,
				PlotOrientation.VERTICAL, true, true, false);

		XYPlot xyPlot = chart.getXYPlot();
		// 设定显示的风格
		xyPlot.setBackgroundPaint(Color.white);
		// 设置图形显示数据区域为灰白色
		xyPlot.setDomainGridlinePaint(Color.white);
		// 设置图形显示区域的竖线为白色
		xyPlot.setRangeGridlinePaint(Color.gray);
		xyPlot.setRangeGridlineStroke(new BasicStroke(0.3f));
		// 设置曲线的颜色
		// xyPlot.setDrawingSupplier(getSupplier());

		/*ValueAxis rangeAxis2 = xyPlot.getRangeAxis(0);
		rangeAxis2.setLabelFont(new Font("微软雅黑", Font.CENTER_BASELINE, 12));*/

		// 显示曲线上的点
		XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyPlot.getRenderer();
		xylineandshaperenderer.setBaseShapesVisible(true);

		NumberAxis rangeAxis = (NumberAxis) xyPlot.getRangeAxis(0);
		NumberFormat numberInstance0 = NumberFormat.getNumberInstance();
		numberInstance0.setMaximumFractionDigits(1);
		rangeAxis.setNumberFormatOverride(numberInstance0);

		// 添加第2个Y轴
		NumberAxis axis2 = new NumberAxis(baseChart.getyName());
		// -- 修改第2个Y轴的显示效果
		axis2.setAxisLinePaint(Color.BLUE);
		axis2.setLabelPaint(Color.BLACK);
		axis2.setTickLabelPaint(Color.BLUE);
		axis2.setLabelFont(new Font("微软雅黑", Font.ROMAN_BASELINE, 12));

		NumberFormat numberInstance = NumberFormat.getNumberInstance();
		numberInstance.setMaximumFractionDigits(1);
		axis2.setNumberFormatOverride(numberInstance);

		xyPlot.setRangeAxis(1, axis2);
		xyPlot.setDataset(1, createXYLineDataset(xyDTOList.subList(1, 2), baseChart));
		xyPlot.mapDatasetToRangeAxis(1, 1);
		// -- 修改第2条曲线显示效果
		XYBarRenderer render2 = new XYBarRenderer();
		render2.setSeriesPaint(0, Color.BLUE);
		xyPlot.setRenderer(1, render2);

		DateAxis domainAxis = new DateAxis();
		domainAxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM"));
		domainAxis.setLowerMargin(0.0);
		domainAxis.setUpperMargin(0.02);
		xyPlot.setDomainAxis(domainAxis);

		return chart;
	}

	/**
	 * 创建按时间为起点的折线图
	 * 
	 * @param baseChart
	 *            baseChartDTO
	 * @param xyDTO
	 *            xy data dto
	 * @return jfreechart
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private JFreeChart createPieChart(BaseChartDTO baseChart, List dataList) {
		PieDataset pieDataSet = getPieDataSet(dataList);

		createJfreeChartTheme();

		JFreeChart chart = ChartFactory.createPieChart(baseChart.getChartName(), pieDataSet, true, true, false);

		PiePlot mPiePlot = (PiePlot) chart.getPlot();

		mPiePlot.setNoDataMessage("无数据");

		// 图片中显示百分比:自定义方式，{0}// 表示选项，// {1}// 表示数值，// {2} 表示所占比例 ,小数点后两位
		mPiePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}", NumberFormat.getNumberInstance(),
				new DecimalFormat("0.00%")));

		mPiePlot.setBackgroundPaint(null);

		return chart;
	}

	/**
	 * 设置jfreechart的字体，防止出现乱码，因为jfreechart的默认字体，中文windows不支持，导致出现乱码， 需要自己明文的指定下。
	 */
	private void createJfreeChartTheme() {

		StandardChartTheme mChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		mChartTheme.setExtraLargeFont(new Font("微软雅黑", Font.CENTER_BASELINE, 14));
		// 设置轴向字体
		mChartTheme.setLargeFont(new Font("微软雅黑", Font.CENTER_BASELINE, 12));
		// 设置图例字体
		mChartTheme.setRegularFont(new Font("微软雅黑", Font.CENTER_BASELINE, 12));
		// 应用主题样式
		ChartFactory.setChartTheme(mChartTheme);
	}

	/**
	 * 设置jfreechart的字体，防止出现乱码，因为jfreechart的默认字体，中文windows不支持，导致出现乱码， 需要自己明文的指定下。
	 */
	private void createJfreeChartMetalTheme() {

		StandardChartTheme mChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		mChartTheme.setExtraLargeFont(new Font("微软雅黑", Font.CENTER_BASELINE, 14));
		// 设置轴向字体
		mChartTheme.setLargeFont(new Font("微软雅黑", Font.CENTER_BASELINE, 12));
		// 设置图例字体
		mChartTheme.setRegularFont(new Font("微软雅黑", Font.CENTER_BASELINE, 12));
		// 应用主题样式
		ChartFactory.setChartTheme(mChartTheme);
	}

	public static DefaultDrawingSupplier getSupplier() {
		return new DefaultDrawingSupplier(new Paint[] { Color.green, Color.red, Color.blue, Color.magenta,
				Color.yellow, Color.orange, Color.cyan, Color.pink, Color.gray, ChartColor.DARK_RED,
				ChartColor.DARK_GREEN, ChartColor.LIGHT_RED, ChartColor.DARK_YELLOW, ChartColor.DARK_MAGENTA,
				ChartColor.DARK_CYAN, Color.lightGray, ChartColor.LIGHT_RED, ChartColor.LIGHT_BLUE,
				ChartColor.LIGHT_GREEN, ChartColor.LIGHT_YELLOW, ChartColor.LIGHT_MAGENTA, ChartColor.LIGHT_CYAN },
				DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
	}

	/**
	 * 创建折线图数据data
	 * 
	 * @param seriesName
	 *            分类名
	 * @param startDate
	 *            起始时间
	 * @param length
	 *            月份长度
	 * @param vList
	 *            值列表
	 * @return IntervalXYDataset
	 */
	private IntervalXYDataset createXYLineDataset(List<XYLineChartDataDTO> xyDTOList, BaseChartDTO baseChart) {

		TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

		for (XYLineChartDataDTO xyDTO : xyDTOList) {

			if (GeneralMethods.getInstance().isEmptyCollects(xyDTO.getDataList())
					|| xyDTO.getLength() > xyDTO.getDataList().size()) {
				xyDTO.setDataList(GeneralMethods.getInstance().fullNullList(xyDTO.getDataList(), xyDTO.getLength()));
			}

			TimeSeries seriesItem = makeSeriesItem(xyDTO, baseChart);

			timeSeriesCollection.addSeries(seriesItem);
		}

		return timeSeriesCollection;
	}

	/**
	 * 构造一条曲线图的数据
	 * 
	 * @param xyDTO
	 *            xyDTO
	 * @param baseChart
	 *            baseChart
	 * @return TimeSeries
	 */
	private TimeSeries makeSeriesItem(XYLineChartDataDTO xyDTO, BaseChartDTO baseChart) {
		TimeSeries series1 = new TimeSeries(xyDTO.getSeriesName());
		Calendar cal = Calendar.getInstance();
		cal.setTime(xyDTO.getStartDate());

		// 取值
		for (int i = 0; i < xyDTO.getLength(); i++) {
			// 同比、环比，从1-12月
			if ("2".equals(baseChart.getyDataType())) {
				if (xyDTO.getDataList().get(i) instanceof BigDecimal) {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)), GeneralMethods
							.getInstance().parsePercentage(((BigDecimal) xyDTO.getDataList().get(i)).doubleValue()));
				} else if (xyDTO.getDataList().get(i) instanceof String) {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)), GeneralMethods
							.getInstance().parsePercentage(Double.parseDouble((String) xyDTO.getDataList().get(i))));
				} else {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)), GeneralMethods
							.getInstance().parsePercentage(Double.parseDouble((String) xyDTO.getDataList().get(i))));
				}
			} else {
				if (xyDTO.getDataList().get(i) instanceof BigDecimal) {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)), ((BigDecimal) xyDTO
							.getDataList().get(i)).doubleValue());
				} else if (xyDTO.getDataList().get(i) instanceof String) {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)),
							Double.parseDouble((String) xyDTO.getDataList().get(i)));
				} else {
					series1.add(new Month(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)),
							Double.parseDouble((String) xyDTO.getDataList().get(i)));
				}
			}

			// 往前 推一个月
			cal.add(Calendar.MONTH, 1);
		}

		return series1;
	}

	/**
	 * 创建用于填充pie图的数据集
	 * 
	 * @return DefaultPieDataset对象
	 */
	public PieDataset getPieDataSet(List<Object> dataList) {
		// 用来填充pie图的数据集
		DefaultPieDataset dataset = new DefaultPieDataset();

		for (Object data : dataList) {
			if (data instanceof String[]) {
				String[] datas = (String[]) data;
				if (datas != null && datas.length >= 2 && GeneralMethods.getInstance().checkDouble(datas[1])) {
					dataset.setValue(datas[0], Double.parseDouble(datas[1]));
				}
			}
		}

		return dataset;
	}

	/**
	 * 创建3D柱状图
	 * 
	 * @param dataset 数据集
	 * @param resultMap 返回的结果集（包含生成的图片名称，用于rtf文件替换占位符为图片）
	 * @param paramMap 参数列表
	 * @param rtfKey 文件占位符key
	 * @param maxYValue Y轴最大坐标
	 */
	public void createBarChart(CategoryDataset dataset,
			Map<String, Object> resultMap, Map<String, Object> paramMap,
			String rtfKey,String chartTitle,double maxYValue) {
	    Color color = new Color(50, 120, 200);
	    
	    // 可疑设置柱状图颜色为红色
	    if(StringUtils.contains(rtfKey, "Susp")){
	        color = new Color(180, 50, 50);
	    }
	    
		// 生成曲线图
		JFreeChart chart = create3DBarChart(dataset, "", "", chartTitle, color,maxYValue);

		try {
			String imageFilePath = CreateRtfTableDataHelper.getInstance()
					.getImagesDir(paramMap, rtfReportDir) + rtfKey + ".png";

			// 生成文档，然后保存到resultMap中，用来替换前端的占位符
			createJpegImg(imageFilePath, chart, KpiValueConst.BAR_PIC);

			resultMap.put(rtfKey, imageFilePath);
		} catch (FwaBusinessException e) {
			logger.error("--createMonCheckChartPic ----", e);
		}
	}

	/**
	 * 3D柱状图
	 * 
	 * @param dataset 数据集
	 * @param xName x轴的说明（如种类，时间等）
	 * @param yName y轴的说明（如速度，时间等）
	 * @param chartTitle 图标题
	 */
	private JFreeChart create3DBarChart(CategoryDataset dataset, String xName,
			String yName, String chartTitle,Color color,double maxYValue) {
		JFreeChart chart = ChartFactory.createBarChart3D(chartTitle, // 图表标题
				xName, // 目录轴的显示标签
				yName, // 数值轴的显示标签
				dataset, // 数据集
				PlotOrientation.VERTICAL, // 图表方向：水平、垂直
				true, // 是否显示图例(对于简单的柱状图必须是false)
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		chart.setBackgroundPaint(Color.WHITE);
		//设置图片边框不可见
		chart.setBorderVisible(false);
		//设置图例位置
		chart.getLegend().setPosition(RectangleEdge.RIGHT);
		//设置图例边框
		chart.getLegend().setBorder(0.0, 0.0, 0.0, 0.0);

		// 设置图标标题字体
		chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 14));

		CategoryPlot plot = chart.getCategoryPlot();
		// 设置图表边框不可见
		plot.setOutlineVisible(false);
		plot.setNoDataMessage("无数据");

		// 设置横轴标题字体
		plot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
		//设置X轴文字显示方向（CategoryLabelPositions.UP_45 : 45°显示）
		plot.getDomainAxis().setCategoryLabelPositions(
				CategoryLabelPositions.UP_45);

		plot.setBackgroundPaint(Color.WHITE);
		// 设置图形显示区域的横线为灰色
		plot.setRangeGridlinePaint(Color.gray);
		//设置横线的宽度
		plot.setRangeGridlineStroke(new BasicStroke(0.3f));
		plot.setRangeGridlinesVisible(true);

		// 设置横轴标记的字体
		plot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
		// 设置横轴标记字体颜色
		plot.getDomainAxis().setTickLabelPaint(Color.BLACK);
		plot.getDomainAxis().setTickMarkInsideLength(0.0f);

		// 设置纵轴标记字体
		plot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));

		// 设置纵轴标记字体
		NumberAxis3D numberAxis3D = (NumberAxis3D) plot.getRangeAxis();
		numberAxis3D
				.setStandardTickUnits(NumberAxis3D.createIntegerTickUnits());
		numberAxis3D.setTickLabelPaint(Color.BLACK);

		// 数据轴精度
		NumberAxis vn = (NumberAxis) plot.getRangeAxis();
		vn.setUpperBound(maxYValue);
		// 自动设置数据轴数据范围
		//vn.setAutoRange(true);
		// 设置纵坐标值的间距为10
		vn.setTickUnit(new NumberTickUnit(0.1));
		// 数据轴的数据标签是否自动确定（默认为true）
		vn.setAutoTickUnitSelection(false);
		DecimalFormat df = new DecimalFormat("0.0%");
		vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式

		// 设置图例字体
		BarRenderer3D renderer3D = (BarRenderer3D) plot.getRenderer();
		renderer3D.setBaseLegendTextFont(new Font("微软雅黑", Font.PLAIN, 12));
		renderer3D.setSeriesPaint(0, Color.ORANGE);

		// 设置柱子宽度
		renderer3D.setMaximumBarWidth(0.05);
		// 设置柱子高度
		renderer3D.setMinimumBarLength(0.2);
		// 设置柱子边框颜色
		renderer3D.setBaseOutlinePaint(Color.BLACK);
		// 设置柱子边框可见
		renderer3D.setDrawBarOutline(false);

		// // 设置柱的颜色
		renderer3D.setSeriesPaint(0, color);

		// 设置每个地区所包含的平行柱的之间距离
		renderer3D.setItemMargin(0.25);

		// 显示每个柱的数值，并修改该数值的字体属性
		renderer3D.setIncludeBaseInRange(true);
		renderer3D
				.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(
						"{2}", new DecimalFormat("0.0%")));
		renderer3D.setBaseItemLabelsVisible(true);
		renderer3D.setBasePositiveItemLabelPosition(new ItemLabelPosition(
				ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
		//设置柱子数值显示字体
		renderer3D.setBaseItemLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
		// 设置柱形图上的文字偏离值
		renderer3D.setItemLabelAnchorOffset(10D);

		plot.setRenderer(renderer3D);
		// 设置柱的透明度
		plot.setForegroundAlpha(1.0f);
		return chart;
	}
}
